package com.cheyunkeji.er;

import android.util.Log;

import java.util.HashMap;
import java.util.Map;

import androidx.fragment.app.Fragment;

/** Created by Michael on 2017/2/16 10:12. */
public class MyFragmentManager {

  public static Map<Class, Fragment> fragSet = new HashMap<>();
  private static MyFragmentManager manager;

  private MyFragmentManager() {}

  public static MyFragmentManager getInstance() {
    if (manager == null) {
      synchronized (MyFragmentManager.class) {
        if (manager == null) {
          manager = new MyFragmentManager();
        }
      }
    }
    return manager;
  }

  /**
   * 根据当前Fragment的Class对象获取到Fragment实体类
   *
   * @param className
   * @return
   */
  public Fragment getFrag(Class className) {
    Fragment frag = null;
    if (fragSet.get(className) != null) {
      frag = fragSet.get(className);
    } else {
      try {
        frag = (Fragment) className.newInstance();
        Log.e(
            MyFragmentManager.class.getSimpleName(),
            "getFrag: " + frag.getClass().getSimpleName() + "=========created by invoke");
      } catch (InstantiationException e) {
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      }
    }
    return frag;
  }

  /**
   * 将Fragment对象添加到HashMap中
   *
   * @param fragName
   * @param fragInstance
   * @return
   */
  public boolean addFrag(Class fragName, Fragment fragInstance) {
    if (fragName != null && fragInstance != null) {
      fragSet.put(fragName, fragInstance);
      return true;
    }
    return false;
  }

  public boolean removeFrag(Class fragName) {
    if (fragName != null && fragSet.containsKey(fragName)) {
      fragSet.remove(fragName);
      return true;
    }
    return false;
  }

  public Map getFragsMap() {
    return fragSet;
  }
}
